<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img
        v-if="!avatar"
        class="the_img"
        src="../../assets/images/avatar.jpg"
        alt=""
      />
      <img v-else class="the_img" :src="avatar" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          type="file"
          accept="image/*"
          style="display: none"
          ref="iptRef"
          @change="onFileChange"
        />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="avatar === ''"
          @click="uploadAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>
<script>
import { updateUserAvatarAPI } from '@/api'
export default {
  name: 'userAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    chooseImg () {
      this.$refs.iptRef.click()
    },
    onFileChange (e) {
      const files = e.target.files
      if (files.length === 0) {
        this.avatar = ''
      } else {
        // 使用URL.createObjURL()来转换文件变成图片地址(纯前端本地)
      // this.avatar = URL.createObjectURL(files[0])
      //  使用**FileReader**来读取选择的前端文件, 转换为base64字符串, 给img标签渲染
        const reader = new FileReader()
        reader.readAsDataURL(files[0])
        reader.onload = (e) => {
          this.avatar = e.target.result
        }
      }
    },
    async uploadAvatar () {
      const { data: res } = await updateUserAvatarAPI(this.avatar)
      if (res.code !== 0) return this.$message.error('上传头像失败！！！')
      this.$store.dispatch('getUserInfo')
      this.$message.success('头像上传成功！！！')
      this.avatar = ''
    }

  }
}
</script>

<style lang="less" scoped>
.imgBox:hover {
  border-color: #409eff;
}
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.the_img {
  width: 350px;
  height: 350px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
}
.the_img:hover {
  border-color: #409eff;
}
</style>
